package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.MaterialInfojk;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.mapper.MaterialInfojkMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.IMaterialInfojkService;
import com.ruoyi.system.utils.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MaterialInfojkServiceImpl implements IMaterialInfojkService {
    @Autowired
    private MaterialInfojkMapper materialInfojkMapper;
    @Autowired
    private RedisService redisService;
    @Resource
    private StringRedisTemplate myRedisTemplate;
    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询句块信息
     *
     * @param id 句块信息主键
     * @return 句块信息
     */
    @Override
    public MaterialInfojk selectMaterialInfojkById(Long id)
    {
        List<SysDictData> dictGList = DictUtils.getDictCache("grade");
        List<SysDictData> dictSList = DictUtils.getDictCache("subject");
        List<SysDictData> dictMList = DictUtils.getDictCache("semester");
        HashMap<String, String> dictGMap = new HashMap<>();
        HashMap<String, String> dictSMap = new HashMap<>();
        HashMap<String, String> dictMMap = new HashMap<>();
        for (SysDictData data:dictGList) {
            dictGMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictMList) {
            dictMMap.put(data.getDictValue(),data.getDictLabel());
        }
        MaterialInfojk info = materialInfojkMapper.selectMaterialInfojkById(id);
        info.setGradeName(dictGMap.get(info.getGrade()+""));
        info.setSubjectName(dictSMap.get(info.getSubject()+""));
        info.setSemesterName(dictMMap.get(info.getSemester()+""));
        return info;
    }

    /**
     * 查询句块信息列表
     *
     * @param materialInfojk 句块信息
     * @return 句块信息
     */
    @Override
    public List<MaterialInfojk> selectMaterialInfojkList(MaterialInfojk materialInfojk)
    {
        List<SysDictData> dictGList = DictUtils.getDictCache("grade");
        List<SysDictData> dictSList = DictUtils.getDictCache("subject");
        List<SysDictData> dictMList = DictUtils.getDictCache("semester");
        HashMap<String, String> dictGMap = new HashMap<>();
        HashMap<String, String> dictSMap = new HashMap<>();
        HashMap<String, String> dictMMap = new HashMap<>();
        for (SysDictData data:dictGList) {
            dictGMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictSList) {
            dictSMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (SysDictData data:dictMList) {
            dictMMap.put(data.getDictValue(),data.getDictLabel());
        }
        List<MaterialInfojk> list = materialInfojkMapper.selectMaterialInfojkList(materialInfojk);
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        for (MaterialInfojk obj:list) {
            obj.setGradeName(dictGMap.get(obj.getGrade()+""));
            obj.setSubjectName(dictSMap.get(obj.getSubject()+""));
            obj.setSemesterName(dictMMap.get(obj.getSemester()+""));
            if (!SysUser.isAdmin(user.getUserId())) {
                obj.setNoAdmin("1");
            }
        }
        return list;
    }

    /**
     * 新增句块信息
     *
     * @param materialInfojk 句块信息
     * @return 结果
     */
    @Override
    public int insertMaterialInfojk(MaterialInfojk materialInfojk)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        materialInfojk.setCreateTime(DateUtils.getNowDate());
        materialInfojk.setUserId(user.getUserId());
        redisService.delCacheMap("MATEJK:DP");
        return materialInfojkMapper.insertMaterialInfojk(materialInfojk);
    }

    /**
     * 修改句块信息
     *
     * @param materialInfojk 句块信息
     * @return 结果
     */
    @Override
    public int updateMaterialInfojk(MaterialInfojk materialInfojk)
    {
        materialInfojk.setCreateTime(DateUtils.getNowDate());
        redisService.delCacheMap("MATEJK:DP");
        return materialInfojkMapper.updateMaterialInfojk(materialInfojk);
    }

    /**
     * 批量删除句块信息
     *
     * @param ids 需要删除的句块信息主键
     * @return 结果
     */
    @Override
    public int deleteMaterialInfojkByIds(Long[] ids)
    {
        redisService.delCacheMap("MATEJK:DP");
        return materialInfojkMapper.deleteMaterialInfojkByIds(ids);
    }

    /**
     * 删除句块信息信息
     *
     * @param id 句块信息主键
     * @return 结果
     */
    @Override
    public int deleteMaterialInfojkById(Long id)
    {
        redisService.delCacheMap("MATEJK:DP");
        return materialInfojkMapper.deleteMaterialInfojkById(id);
    }

    @Override
    public String importInfo(List<MaterialInfojk> infoList, Boolean isUpdateSupport, SysUser user, String fz) {
        if (StringUtils.isNull(infoList) || infoList.size() == 0)
        {
            throw new CustomException("导入句块信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<SysDictData> dictListT = DictUtils.getDictCache("exam_type");
        List<SysDictData> dictListR = DictUtils.getDictCache("rank");
        HashMap<String, Integer> typeMap = new HashMap<>();
        HashMap<String, Long> schoolMap = new HashMap<>();
        for (SysDictData dict : dictListT) {
            typeMap.put(dict.getDictLabel(), Integer.valueOf(dict.getDictValue()));
        }
        Map<Object, Object> mapDepValue = myRedisTemplate.opsForHash().entries("SCHOOL:DP");
        List<SysDept> schoolList = null;
        if (null == mapDepValue.get("ALL")||(null!=mapDepValue.get("ALL")&&"[]".equals(mapDepValue.get("ALL").toString()))||mapDepValue.size()<=0) {
            SysDept paramDept = new SysDept();
            paramDept.setParentId(Long.valueOf(0L));
            paramDept.setStatus("0");
            paramDept.setDelFlag("0");
            schoolList = deptMapper.selectDeptListDp(paramDept);
            Map<String, String> map = new HashMap<>();
            map.put("ALL", JSON.toJSONString(schoolList));
            myRedisTemplate.opsForHash().putAll("SCHOOL:DP", map);
        } else {
            schoolList = JSON.parseArray(mapDepValue.get("ALL").toString(), SysDept.class);
        }
        for (SysDept dept : schoolList) {
            schoolMap.put(dept.getDeptName(), dept.getDeptId());
        }
        for (MaterialInfojk info : infoList)
        {
            if (null==info.getMaterialName()||"".equals(info.getMaterialName())||
                    null==info.getMaterialKey()||"".equals(info.getMaterialKey())||
                    null==info.getVersion()||"".equals(info.getVersion())||
                    null==info.getIsFree()||"".equals(info.getIsFree())) {
                failureNum++;
                String msg = "<br/>" + failureNum + "句块 " + info.getMaterialName() + " 导入失败：缺少带*必填项";
                failureMsg.append(msg);
                continue;
            }
            if (info.getIsFree()!=1&&(null==info.getAmount()&&info.getAmount().compareTo(BigDecimal.ZERO)<=0)) {
                failureNum++;
                String msg = "<br/>" + failureNum + "句块 " + info.getMaterialName() + " 导入失败：缺少金额";
                failureMsg.append(msg);
                continue;
            }
            try
            {
                successNum++;
                successMsg.append("<br/>" + successNum + "句块信息 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "句块信息 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
